package cn.tedu.sp11.filter;


import cn.tedu.web.util.JsonResult;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.constants.ZuulConstants;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import jdk.nashorn.internal.parser.Token;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

@Component
public class AccessFilter extends ZuulFilter {
    //过滤器类型:pre,post,routing,error
    @Override
    public String filterType() {
        //return "pre";
        return FilterConstants.PRE_TYPE;
    }

    //过滤器插入的位置
    //在第五个过滤器中在上下文中添加了serviceid
    //在后面过滤器中才能访问serviceid
    @Override
    public int filterOrder() {
        return 6;
    }

    //对用户胡德请求进行判断,是否要执行过滤代码
    @Override
    public boolean shouldFilter() {
        /**
         * 只对item-service调用进行过滤--返回true;
         * 如果执行的是user或order不执行过滤--返回false;
         * */
        //获得调用服务id{item-service/user-service/..}
        RequestContext ctx = RequestContext.getCurrentContext();
        String serviceId  =(String) ctx.get(FilterConstants.SERVICE_ID_KEY);
        //equalsIgnoreCase忽略大小写进行比较
         return "item-service".equalsIgnoreCase(serviceId);
        //return true;
    }

    //过滤代码
    @Override
    public Object run() throws ZuulException {
        //http://localhost:3001/item-service/123abc  没有登录,不允许访问
        //http://localhost:3001/item-service/123abc?token=aaa  以登录,允许访问
        //获得request对象
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        //接收token参数
        String token = request.getParameter("token");

        //如果没有token,阻止让问,并向客户端返回响应
        if (StringUtils.isBlank(token)){
            //阻止继续访问--关闭发送zuul响应
            ctx.setSendZuulResponse(false);
            //Jsonresult{code:401,msg:no login,data:null}
            String json = JsonResult.err()
                    .code(JsonResult.EXCEPTION)
                    .msg("not login")
                    .toString();

            ctx.addZuulResponseHeader("Contrnt-Type", "application/json;charset=UTF-8");
            ctx.setResponseBody(json);
        }
        return null;//返回值没有任何作用;
    }
}
